﻿using Microsoft.Web.Administration;
using Microsoft.WindowsAzure.ServiceRuntime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;

namespace Wams.Server
{
    public class WamsWebRole: RoleEntryPoint
    {
        public override void OnStop()
        {
            WamsCore.Stop();
        }
        public override void Run()
        {
            WamsCore.Initialise();
            WamsCore.WaitToRecycle();
        }

        public override bool OnStart()
        {
            RoleEnvironment.StatusCheck += RoleEnvironment_StatusCheck;
            return true;
        }

        public DateTime LastSave = DateTime.MinValue;
        public DateTime LastClearExpired = DateTime.MinValue;
        void RoleEnvironment_StatusCheck(object sender, RoleInstanceStatusCheckEventArgs e)
        {
            if (WamsCore.InstanceState == null || WamsCore.InstanceState.IsBusy) e.SetBusy();

            if (LastSave < DateTime.Now.AddMinutes(-1))
            {
                LastSave = DateTime.Now;
                try
                {
                    WamsCore.InstanceState.Save();
                }
                catch (Exception ex)
                { Logger.Log(LogLevel.Critical, "Instance State Save failed: " + ex.ToString()); }

                try
                {
                    lock (WamsCore._syncSites)
                    {
                        Parallel.ForEach(WamsCore.Sites.Values, site =>
                            {
                                site.State.Save();
                            });
                    }
                }
                catch (Exception ex)
                { Logger.Log(LogLevel.Critical, "Site State Save failed: " + ex.ToString()); }
            }
            if (LastClearExpired < DateTime.Now.AddMinutes(-5))
            {
                LastClearExpired = DateTime.Now;
                try { WamsInstanceState.DeleteExpired(); }
                catch (Exception ex)
                { Logger.Log(LogLevel.Critical, "Expired instance state delete failed: " + ex.ToString()); }

                try { WamsSiteState.DeleteExpired(); }
                catch (Exception ex)
                { Logger.Log(LogLevel.Critical, "Expired site state delete failed: " + ex.ToString()); }
            }

        }

    }
}